package pers.yurwisher.rubick.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义响应过滤器
 *
 * @author yq
 * @date 2021年5月8日 10:02:52
 */
@Slf4j
@Component
public class CustomGateWayResponseFilter extends AbstractGateWayFilter {


    private final ModifyResponseBodyGatewayFilterFactory modifyResponseBodyGatewayFilterFactory;
    private final ModifyResponseBodyGatewayFilterFactory.Config config;

    public CustomGateWayResponseFilter(ModifyResponseBodyGatewayFilterFactory modifyResponseBodyGatewayFilterFactory) {
        this.modifyResponseBodyGatewayFilterFactory = modifyResponseBodyGatewayFilterFactory;
        this.config = this.filterConfig();
    }

    private ModifyResponseBodyGatewayFilterFactory.Config filterConfig() {
        ModifyResponseBodyGatewayFilterFactory.Config config = new ModifyResponseBodyGatewayFilterFactory.Config();
        config.setNewContentType(MediaType.APPLICATION_JSON_VALUE);
        config.setRewriteFunction(String.class, String.class, (exchange, resp) -> {
            //此处可修改响应结果
            log.info("[{}] responseBody:[{}]", exchange.getRequest().getId(), resp);
            return Mono.just(resp);
        });
        return config;
    }

    @Override
    protected boolean ignoreExpress(ServerWebExchange exchange) {
        return false;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return modifyResponseBodyGatewayFilterFactory.apply(this.config).filter(exchange, chain);
    }

    @Override
    public int getOrder() {
        return -90;
    }
}
